import Vue from 'vue'
import Router from 'vue-router'
import Login from '../components/login/login.vue'
import Home from '../components/home/home.vue'
import Users from '../components/users/users.vue'
import Right from '../components/right/right.vue'
import Role from '../components/right/role.vue'
import Goodslist from '@/components/goods/goodslist.vue'
import Goodsadd from '@/components/goods/Goodsadd.vue'
import Cateparams from '@/components/goods/cateparams.vue'
import Goodscate from '@/components/goods/goodscate.vue'
import Order from '@/components/order/order.vue'
import Reports from '@/components/reports/reports.vue'
import { Message } from 'element-ui'

Vue.use(Router)

const router = new Router({
  mode: 'hash',
  routes: [
    {
      name: 'login',
      path: '/login',
      component: Login
    },
    {
      name: 'home',
      path: '/',
      component: Home,
      children: [{
        name: 'users',
        path: '/users',
        component: Users
      },
      {
        name: 'rights',
        path: '/rights',
        component: Right
      },
      {
        name: 'roles',
        path: '/roles',
        component: Role
      },
      {
        name: 'goods',
        path: '/goods',
        component: Goodslist
      },
      {
        name: 'goodsadd',
        path: '/goods',
        component: Goodsadd
      },
      {
        name: 'params',
        path: '/params',
        component: Cateparams
      },
      {
        name: 'categories',
        path: '/categories',
        component: Goodscate
      },
      {
        name: 'orders',
        path: '/orders',
        component: Order
      },
      {
        name: 'reports',
        path: '/reports',
        component: Reports
      },
      ]
    }
  ]
})

//在路由生效之前，统一判断token
//路由守卫 在路由生效之前
//路由/导航守卫
// to--》要去的路由
// from--》当前的路由配置
router.beforeEach((to, from, next) => {
  // 如果要去登录--》next
  if (to.path === '/login') {
    next();
  } else {
    const token = localStorage.getItem("token");
    // 如果去的不是登录，判断token
    if (!token) {
      Message.warning('请先登录！');
      // 如果token没有--》login
      router.push({ name: 'login' });
      return;
    }

    // 如果有--》next（）
    next();
  }

})

export default router